package com.bhkj.pdjhbgnewproject.common.work;


import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import com.bhkj.pdjhbgnewproject.common.bean.SimpleBean;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class WorkHelper {
    private static String RELAUNCHER = "relauncher";

    /**
     * 启动定时任务在指定时间重启App
     */
    public static void reLauncherWork() {
        //网络连接状态下，通过Api获取服务器指定的时间
        obtainFromNetTime(4,2);
        NetworkUtils.registerNetworkStatusChangedListener(new NetworkUtils.OnNetworkStatusChangedListener() {
            @Override
            public void onDisconnected() {
                LogUtils.d("网络未连接");
            }

            @Override
            public void onConnected(NetworkUtils.NetworkType networkType) {
                obtainFromNetTime(4,2);
            }
        });
    }


    private static void executeTask(int hours,int mins){
        Calendar currentDate = Calendar.getInstance();
        Calendar dueDate = Calendar.getInstance();

        // 设置在大约 指定的小时，分钟 执行
        dueDate.set(Calendar.HOUR_OF_DAY, hours);
        dueDate.set(Calendar.MINUTE, mins);
        dueDate.set(Calendar.SECOND, 1);
        if (dueDate.before(currentDate)) {
            dueDate.add(Calendar.HOUR_OF_DAY, 24);
        }
        long timeDiff = dueDate.getTimeInMillis() - currentDate.getTimeInMillis();
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(RelauncherAppWork.class).setInitialDelay(timeDiff, TimeUnit.MILLISECONDS)
                .addTag(RELAUNCHER).build();
        LogUtils.d("延迟时间：" +timeDiff+"-"+ (timeDiff / (1000 * 60 * 60)));
        WorkManager.getInstance().beginUniqueWork(RELAUNCHER, ExistingWorkPolicy.REPLACE, oneTimeWorkRequest).enqueue();
    }

    private static void obtainFromNetTime(final int hours, final int mins) {
        EasyHttp.get("machine/getRestartTime")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showLong("获取重启设备时间失败:" + e.getMessage() + "-" + e.getCode());
                        executeTask(hours,mins);
                    }

                    @Override
                    public void onSuccess(String s) {
                        handleWorkSuccess(s, hours, mins);
                    }
                });
    }

    private static void handleWorkSuccess(String s, int hours, int mins) {
        SimpleBean simpleBean = GsonUtils.fromJson(s, SimpleBean.class);
        if (simpleBean==null){
//            executeTask(hours,mins);
            return;
        }
        if (simpleBean.isSuccess()){
            Date date = TimeUtils.string2Date(simpleBean.getDatas(), "hh:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            executeTask(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
        }else{
            executeTask(hours,mins);
        }
    }

    /**
     * 取消重启App任务
     */
    public static void cancelWorkRelauncherApp() {
        WorkManager.getInstance()
                .cancelUniqueWork(RELAUNCHER);
    }
}
